package leetcode.tree;

import java.util.HashMap;
import java.util.Map;

public class ConstructBinaryTreeFromPreorderAndInorderTraversal105 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {
        public TreeNode buildTree(int[] preorder, int[] inorder) {
            Map<Integer, Integer> map = new HashMap<>();
            for (int i = 0; i < inorder.length; i++) {
                map.put(inorder[i], i);
            }
            return buildTree(0, inorder.length - 1, 0, preorder.length - 1,  map, preorder);
        }

        public TreeNode buildTree(int inorderStart, int inorderEnd, int preorderStart, int preorderEnd, Map<Integer, Integer> map, int[] preorder) {
            if (preorderStart > preorderEnd || inorderStart > inorderEnd) {
                return null;
            }
            int valOfRoot = preorder[preorderStart];
            int indexOfRoot = map.get(valOfRoot);
            TreeNode root = new TreeNode(valOfRoot);
            root.left = buildTree(inorderStart, indexOfRoot - 1, preorderStart + 1, preorderStart + indexOfRoot - inorderStart, map, preorder);
            root.right = buildTree(indexOfRoot + 1, inorderEnd, preorderStart + indexOfRoot - inorderStart + 1, preorderEnd, map, preorder);
            return root;
        }
    }
}
